package com.jinlejia.erp.ui.home;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.ZoomControls;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.XXPermissions;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.PoiAdapter;
import com.jinlejia.erp.bean.MeetPlaceBean;
import com.jinlejia.erp.databinding.ActivityMeetingPlaceBinding;
import com.jinlejia.erp.ui.common.PermissionDialog;
import com.jinlejia.erp.ui.customer.PoiSearchActivity;
import com.jinlejia.erp.utils.DbUtil;
import com.weight.CustomToast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


/**
 * 见面地点（Activity）
 */

public class MeetingPlaceActivity extends AppCompatActivity {
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    BaiduMap mBaiduMap;
    MapStatus ms;
    private ArrayList<MeetPlaceBean> poiList = new ArrayList<>();
    private PoiAdapter adapter;
    private String city;

    PermissionDialog permissionDialog;

    private ActivityMeetingPlaceBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_meeting_place);
        binding.btBack.setOnClickListener(this::onClick);
        binding.etSearchText.setOnClickListener(this::onClick);
        binding.tvSearch.setOnClickListener(this::onClick);
        init();
    }

    private void init() {
        binding.yfRecycler.setLayoutManager(new LinearLayoutManager(this));
        binding.yfRecycler.setHasFixedSize(true);
        adapter = new PoiAdapter(poiList);
        binding.yfRecycler.setAdapter(adapter);
        adapter.setOnAddressSelectListener(mpb -> {
            GeoCoder mGeoCoder = GeoCoder.newInstance();
            GeoCodeOption mGeoCodeOption = new GeoCodeOption();
            mGeoCodeOption.address(mpb.getAddress());
            mGeoCodeOption.city(mpb.getCity());
            mGeoCoder.geocode(mGeoCodeOption);
            // 设置查询结果监听者
            mGeoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
                @Override
                public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                    mBaiduMap.clear();
                    // 定义marker坐标点
                    LatLng point = new LatLng(geoCodeResult.getLocation().latitude,  geoCodeResult.getLocation().longitude);
                    View view;
                    if( adapter.getData().indexOf(mpb) != 0 ) {
                        view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_meet_location, null);

                        TextView tv_name = view.findViewById(R.id.location_name);
                        tv_name.setText(mpb.getName());
                    }else{
                        view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.poi_item_layout, null);

                        TextView tv_name = view.findViewById(R.id.name);
                        String txt = "我" + mpb.getName() + "附近 >";
                        SpannableStringBuilder builder = new SpannableStringBuilder(txt);
                        ForegroundColorSpan textSpan = new ForegroundColorSpan(getResources().getColor(R.color.textColor));
                        builder.setSpan(textSpan, 2, txt.length() - 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        tv_name.setText(builder);
                    }
                        BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromBitmap(getViewBitmap(view));
                        // 构建markerOption，用于在地图上添加marker
                        OverlayOptions options = new MarkerOptions()//
                                .position(point)// 设置marker的位置
                                .icon(markerIcon)// 设置marker的图标
                                .zIndex(9)// 設置marker的所在層級
                                .draggable(true);// 设置手势拖拽
                        // 在地图上添加marker，并显示
                        mBaiduMap.addOverlay(options);
                        ms = new MapStatus.Builder().target(point).zoom(20).build();
                        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));

                }

                @Override
                public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {

                }
            });
        });

        // 定位初始化
        mLocClient = new LocationClient(getApplicationContext());
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true); // 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setAddrType("all");
        option.setIsNeedAddress(true);
        option.setScanSpan(60 * 60 * 1000); // 多长时间进行一次请求
        option.setPriority(LocationClientOption.NetWorkFirst); //设置网络优先
        option.setIsNeedLocationDescribe(true);
//        option.setIsNeedLocationPoiList(true);
        mLocClient.setLocOption(option);

        View child = binding.mapview.getChildAt(1);
        if (child != null && (child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);
        }

        //地图上比例尺
        binding.mapview.showScaleControl(false);
        // 隐藏缩放控件
        binding.mapview.showZoomControls(false);

        mBaiduMap = binding.mapview.getMap();
        if (null == permissionDialog)
            permissionDialog = new PermissionDialog(this);
        XXPermissions.with(this)
                .permission(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_WIFI_STATE,
                        Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        System.out.println(granted.toString());
                        mLocClient.start();
                        if (isAll && permissionDialog.isShowing()) {
                            permissionDialog.dismiss();
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        if (null != permissionDialog && !permissionDialog.isShowing())
                            permissionDialog.show();
                        permissionDialog.setConfirmListener(new PermissionDialog.OnConfirmListener() {
                            @Override
                            public void confirm() {
                                XXPermissions.gotoPermissionSettings(MeetingPlaceActivity.this);
                            }
                        });
                    }
                });
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.et_search_text:
                Intent intent = new Intent(MeetingPlaceActivity.this, PoiSearchActivity.class);
                intent.putExtra("city", city);
                intent.putExtra("property", getIntent().getStringExtra("property"));
                startActivity(intent);
                break;
            case R.id.tv_search:
                Intent data = new Intent();
                data.putExtra("address", adapter.getData().get(adapter.cur_position).getName());
                data.putExtra("city", adapter.getData().get(adapter.cur_position).getCity());
                setResult(RESULT_OK, data);
                finish();
                break;
            default:
                break;
        }
    }


    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location.getLocType() == 62){
                CustomToast.showToast(MeetingPlaceActivity.this,"定位失败，请检查GPS定位是否开启",1500);
            }else if (location.getLocType() == 63){
                CustomToast.showToast(MeetingPlaceActivity.this,"网络异常，请检查网络是否正常",1500);
            }else if (location.getLocType() == 161 || location.getLocType() == 61) {
                //网络定位或者GPS定位成功
                city = location.getCity();
                LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
                ms = new MapStatus.Builder().target(ll).zoom(20).build();
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(ms));
                mBaiduMap.getUiSettings().setAllGesturesEnabled(true);

                View view = LayoutInflater.from(getApplicationContext()).inflate(R.layout.poi_item_layout, null);

                TextView tv_name = view.findViewById(R.id.name);
                String txt = "我" + location.getLocationDescribe() + ">";
                SpannableStringBuilder builder = new SpannableStringBuilder(txt);
                ForegroundColorSpan textSpan = new ForegroundColorSpan(getResources().getColor(R.color.textColor));
                builder.setSpan(textSpan, 2, txt.length() - 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                tv_name.setText(builder);

                BitmapDescriptor markerIcon = BitmapDescriptorFactory.fromBitmap(getViewBitmap(view));
                OverlayOptions oo = new MarkerOptions().position(ll).icon(markerIcon).zIndex(9).draggable(true);
                mBaiduMap.addOverlay(oo);

//            if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
//                for (int i = 0; i < location.getPoiList().size(); i++) {
//                    Poi poi = (Poi) location.getPoiList().get(i);
//                    LogUtil.d(poi.getName() + "   " + poi.describeContents() + "   " + poi.getId());
//                    poiList.add( poi.getName() );
//                }
//            }
                poiList.addAll(DbUtil.getDB(MeetingPlaceActivity.this).single().query(MeetPlaceBean.class));
                Collections.reverse(poiList);
                MeetPlaceBean mpb = new MeetPlaceBean();
                if (null != location.getLocationDescribe())
                mpb.setName(location.getLocationDescribe().replaceFirst("在","").replace("附近",""));
                if (null != location.getAddrStr())
                mpb.setAddress(location.getAddrStr());
                if (null != location.getCity())
                mpb.setCity(location.getCity());
                poiList.add(0, mpb);
                adapter.setData(poiList);
                //默认选中第一个
                adapter.cur_position = 0;
            }
        }
    }

    private Bitmap getViewBitmap(View addViewContent) {

        addViewContent.setDrawingCacheEnabled(true);

        addViewContent.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        addViewContent.layout(0, 0, addViewContent.getMeasuredWidth(), addViewContent.getMeasuredHeight());

        addViewContent.buildDrawingCache();
        Bitmap cacheBitmap = addViewContent.getDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

        return bitmap;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocClient.stop();
        binding.mapview.onDestroy();
    }
}
